package com.acme.bankapp.domain.email.impl;

import com.acme.bankapp.domain.email.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class QueueImpl implements Queue {

	List<Email> mails = new ArrayList<Email>();
	private boolean isClosing = false;
	
	public boolean isClosing() {
		return isClosing;
	}

	public void addEmail(Email email) {
		synchronized (mails) {
			if (!isClosing)
			{
				mails.add(email);
				mails.notify();
			}
		}		
	}

	public void close() {
		synchronized (mails) {
			isClosing = true;
			mails.notifyAll();		
		}
	}

	public Email getEmail() throws InterruptedException {	
		Email email = null;
		
		synchronized (mails) {
			while(mails.isEmpty() && !isClosing) {
				mails.wait();	
			}
			
			if (!mails.isEmpty())
				email =  mails.remove(0);				
		}
		
		return email;
	}
	
	public boolean isEmpty() {
		synchronized (mails) {
			return mails.isEmpty();
		}
	}	
}
